import {
  Client, LocalAddress, CryptoUtils, LoomProvider
} from 'loom-js'

import Web3 from 'web3'
import MyCoin from '../contracts/MyCoin'
import { Buffer } from 'buffer';
Buffer

export default class Contract {

  async loadContract() {
    this.onEvent = null
    this._createClient()
    this._createCurrentUserAddress()
    this._createWebInstance()
    // await this._getCurrentNetwork()
    await this._createWeb3()
    
    return {
      currentUserAddress:this.currentUserAddress,
      privateKey: CryptoUtils.Uint8ArrayToB64(this.privateKey),
      publicKey: LocalAddress.fromPublicKey(this.publicKey).toString()
    }
    // console.log('lee==============,contract')
  }
  async _createWeb3(){
    const networkId = await this._getCurrentNetwork()
    this.currentNetwork = MyCoin.networks[networkId];
    const coinABI = MyCoin.abi;
    this.coinInstance = new this.web3.eth.Contract(coinABI, this.currentNetwork.address, {
      from: this.currentUserAddress
    })
    this.coinInstance.events.allEvents((err, event) => {
      if (err) console.error('Error on event', err)
      else {
        console.log(event)
        this.user = event.returnValues;
        if (this.onEvent) {
          this.onEvent(event.returnValues)
        }
      }
    });
  }

  _createClient() {
    this.privateKey = CryptoUtils.generatePrivateKey()
    this.publicKey = CryptoUtils.publicKeyFromPrivateKey(this.privateKey)
    let writeUrl = 'ws://47.104.151.59:46658/websocket'
    let readUrl = 'ws://47.104.151.59:46658/queryws'
    // let writeUrl = 'ws://127.0.0.1:46658/websocket'
    // let readUrl = 'ws://127.0.0.1:46658/queryws'
    let networkId = 'default'

    if (process.env.NETWORK == 'extdev') {
      writeUrl = 'ws://extdev-plasma-us1.dappchains.com:80/websocket'
      readUrl = 'ws://extdev-plasma-us1.dappchains.com:80/queryws'
      networkId = 'extdev-plasma-us1'
    }

    this.client = new Client(networkId, writeUrl, readUrl)

    this.client.on('error', msg => {
      console.error('Error on connect to client', msg)
      console.warn('Please verify if loom command is running')
    })
  }

  _createCurrentUserAddress() {
    this.currentUserAddress = LocalAddress.fromPublicKey(this.publicKey).toString()
  }

  _createWebInstance() {
    this.loomP = new LoomProvider(this.client, this.privateKey);
    this.web3 = new Web3(this.loomP)
  }

  addEventListener(fn) {
    this.onEvent = fn
  }
  async _getCurrentNetwork() {
    return Promise.resolve('default')
  }
  

  // 貨幣-----------------------------------------------------


  // 創建用户
  async createUser(amount) {

     await this.coinInstance.methods.createUser( 
      this.currentUserAddress
      ).send(
        {from:this.currentUserAddress}
    )
    return '您已经创建用户：'+ this.user.current + '   用户地址 : ' + this.user._sender + '  账户余额：' + this.user.amount
    
  }

  async createLoomUser(privateKey) {
    this.loomP.addAccounts(privateKey);
  }

  async getAllUsers() {
    let usersList= await this.coinInstance.methods.getRequests( ).call(
       
    );
    // console.log(usersList)
  }
  
  
  
}
